package com.software.sqlite.service.impl;

import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import cn.hutool.poi.excel.StyleSet;
import com.alibaba.fastjson.JSON;
import com.software.sqlite.api.admin.v1.vo.AdminLoginUserVO;
import com.software.sqlite.api.admin.v1.vo.AdminV1Result;
import com.software.sqlite.common.BaseMapper;
import com.software.sqlite.common.CommonContant;
import com.software.sqlite.entity.AutoRecharge;
import com.software.sqlite.entity.SonicWallEntity;
import com.software.sqlite.entity.TbMovieServer;
import com.software.sqlite.entity.TbMovieUserBill;
import com.software.sqlite.mapper.TbMovieServerMapper;
import com.software.sqlite.mapper.TbMovieUserBillMapper;
import com.software.sqlite.service.ITbMovieUserBillService;
import com.software.sqlite.task.FlowDataScheduledTask;
import com.software.sqlite.utils.CommonUtils;
import com.software.sqlite.utils.DateUtils;
import com.software.sqlite.utils.FileUtils;
import com.software.sqlite.utils.SSHCommUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.util.*;

@Service
@Slf4j
public class TbMovieUserBillService extends BaseService<TbMovieUserBill,String,Object> implements ITbMovieUserBillService {

    @Resource
    private TbMovieUserBillMapper mapper;
    @Resource
    private TbMovieServerMapper movieServerMapper;
    @Override
    protected BaseMapper<TbMovieUserBill> getBaseMapper() {
        return mapper;
    }
    @Value("${file.basedir}")
    private String basedir;
    @Resource
    private HttpServletRequest request;


    @Override
    public void autoRecharge() {
        try{
            if(!FlowDataScheduledTask.isRunning){
                FlowDataScheduledTask.isRunning=true;
                //只有流量充值才能自动充值
                List<AutoRecharge> orderList=mapper.selectRechargeList();
                if(orderList.size()>0){
                    for(AutoRecharge payOrder:orderList){
                        log.info("============================bill shipName "+payOrder.getShipName()+" orderNo "+payOrder.getOrderNo()+" username "+payOrder.getUserAccount()+" start==============================");
                        Integer errorCount=CommonUtils.parseIntegerData(payOrder.getErrorCount(),0);
                        List<TbMovieServer> serverList=movieServerMapper.selectListBySQL(new TbMovieServer());
                        if(serverList.size()>0){
                            TbMovieServer movieServer=serverList.get(0);
                            if(errorCount<6){
                                SonicWallEntity sonicWall=new SonicWallEntity();
                                sonicWall.setRemoteIp(movieServer.getSonicWallIp());
                                sonicWall.setRemotePort(movieServer.getSonicWallPort());
                                sonicWall.setRemoteUserName(movieServer.getSonicWallUserName());
                                sonicWall.setRemotePassword(movieServer.getSonicWallPassword());
                                sonicWall.setUser(payOrder.getUserAccount());
                                sonicWall.setPassword(payOrder.getUserPassword());
                                sonicWall.setReceiveData(payOrder.getReceiveData());
                                sonicWall.setTransmitData(payOrder.getTransmitData());
                                sonicWall.setQuotaCycle(payOrder.getQuotaCycle());
                                sonicWall.setSessionLifetime(payOrder.getSessionLifetime());
                                sonicWall.setAccountLifetime(payOrder.getAccountLifetime());
                                String[] result= SSHCommUtils.execSonicWall(sonicWall);
                                String handleUserName="系统机器人";
                                String handleFlag="-1";
                                String handleMessage="系统自动充值失败！";
                                String errorResult="";
                                errorCount++;
                                if(result==null){
                                    handleMessage="系统自动充值失败：船舶"+payOrder.getShipName()+"远程充值连接不上！";
                                }else{
                                    if(result.length>=5){
                                        handleMessage="系统自动充值成功！";
                                        handleFlag="1";
                                        String res=result[result.length-5];
                                        errorResult=res;
                                        if(res.contains("Error"))
                                        {
                                            handleFlag="-1";
                                            handleMessage="系统自动充值失败：指令错误！";
                                        }
                                    }
                                }
                                mapper.updateOrderByAuto(payOrder.getBillId(),handleUserName,handleMessage,handleFlag,errorCount,errorResult);
                                Thread.sleep(6*1000);
                            }
                        }else{
                            String handleUserName="系统机器人";
                            String handleFlag="-1";
                            String handleMessage="系统自动充值失败：船舶"+payOrder.getShipName()+"没有sonicwall设备，不能充值！";
                            errorCount++;
                            mapper.updateOrderByAuto(payOrder.getBillId(),handleUserName,handleMessage,handleFlag,errorCount,handleMessage);
                            log.info("船舶"+payOrder.getShipName()+"没有sonicwall设备，不能充值");
                        }
                        log.info("============================payOrder end==============================");
                    }
                }
            }

        }catch (Exception e){
            log.error("autoRecharge()："+e.getMessage());
        }finally {
            FlowDataScheduledTask.isRunning=false;
        }
    }

    @Override
    public AdminV1Result edit(TbMovieUserBill model) {
        AdminV1Result result=new AdminV1Result<>();
        Integer code=1;
        String msg="保存失败";
        try{

            if(model!=null){
                AdminLoginUserVO loginUser=this.getLoginUser(model.getToken());
                model.setUseStatus("normal");
                Integer totalFee=(int)(CommonUtils.parseDoubleData(model.getBillAmount().setScale(2))*100);
                model.setTotalFee(totalFee);
                model.setDataResource("ship");
                if(model.getBillId()==null){
                    String orderNo=DateUtils.format(new Date(), DateUtils.YMD_DASH_WITH_MITIME_STR);
                    model.setOrderNo(orderNo);
                    model.setOrderFlag(0);
                    model.setUuid(UUID.randomUUID().toString().replaceAll("-","").toLowerCase());
                    model.setCreateTime(new Date());
                    model.setCreateAdminId(loginUser.getUserId());
                    add(model);
                }else{
                    model.setUpdateTime(new Date());
                    model.setUpdateAdminId(loginUser.getUserId());
                    model.setCreateTime(new Date());
                    model.setCreateAdminId(loginUser.getUserId());
                    update(model);
                }
                code=0;
                msg="保存成功";
            }
        }catch (Exception e){
            log.error(e.getMessage(),e);
        }
        result.setMsg(msg);
        result.setCode(code);
        return result;
    }

    @Override
    public AdminV1Result batchAdd(HttpServletRequest request) {
        HttpSession session = request.getSession();
        AdminV1Result result=new AdminV1Result<>();
        Integer code=1;
        String msg="保存失败";
        try {
            List<Map<String,Object>> dataList= (List<Map<String, Object>>) session.getAttribute(CommonContant.ADMIN_BATCH_MOVIE_USER_BILL_SESSION);
            log.info(JSON.toJSONString(dataList));
            if(dataList.size()==0){
                msg="请重新导入数据！";
                result.setMsg(msg);
                result.setCode(code);
                return result;
            }
            code=0;
            msg="保存成功";
        }catch (Exception e){
            e.printStackTrace();
        }
        result.setMsg(msg);
        result.setCode(code);
        return result;
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public synchronized AdminV1Result importData(MultipartFile file, Map<String, Object> paramsMap, HttpServletRequest request) {
        HttpSession session = request.getSession();
        AdminV1Result result=new AdminV1Result<>();
        Map<String,Object> resultMap=new HashMap<>();
        List<Map<String,Object>> dataList=new ArrayList<>();
        Integer code=1;
        String msg="导入失败";
        try{
            String token= CommonUtils.parseStringData(paramsMap.get("token"));
            AdminLoginUserVO loginUser=this.getLoginUser(token);
            String ext = FileUtils.getExtend(file.getOriginalFilename());
            String today= DateUtils.format(new Date(),DateUtils.YMD);
            String temp="school/"+today+"/";
            String originPath=basedir+temp;
            FileUtils.existOrmkdir(originPath);
            String fileName=DateUtils.format(new Date(), DateUtils.YMD_DASH_WITH_MITIME_STR);
            String detailDestination=originPath+fileName+"."+ext;
            File detailFile = new File(detailDestination);
            if (!detailFile.getParentFile().exists()) {
                detailFile.getParentFile().mkdirs();
            }
            try {
                file.transferTo(detailFile);
            } catch (Exception e) {
                if(detailFile.exists()){
                    detailFile.delete();
                }
            }
            if(detailFile!=null){
                ExcelReader reader = ExcelUtil.getReader(detailFile);
                int startRowIndex=2;
                List<List<Object>> readAll = reader.read(startRowIndex);
                if(readAll.size()>0){
                    int rowSize=3;
                    int idex=1;
                    for(List<Object> list:readAll){
                        Map<String,Object> mapObject=new LinkedHashMap<>();
                        int rowIndex=0;
                        mapObject.put("rowIndex0",idex);
                        String errMsg="√";
                        while (rowIndex<rowSize)
                        {
                            String rowValue=CommonUtils.parseStringData(list.get(rowIndex));
                            mapObject.put("rowIndex"+(rowIndex+1),rowValue);
//                            if(idex==8){
//                                errMsg="第"+idex+"行，账号重复！";
//                            }
                            rowIndex++;
                        }
                        mapObject.put("errMsg",errMsg);
                        dataList.add(mapObject);
                        idex++;

                    }
                    code=0;
                    msg="导入成功";
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        session.setAttribute(CommonContant.ADMIN_BATCH_MOVIE_USER_BILL_SESSION, dataList);
        result.setMsg(msg);
        result.setCode(code);
        result.setCount(dataList.size());
        result.setData(dataList);
        return result;
    }


    @Override
    public String exportData(TbMovieUserBill model) throws Exception {
        String url="";
        try {
            String path = request.getContextPath();
            List<TbMovieUserBill> list=selectListBySQL(model);
            String timeStr= DateUtils.format(new Date(), DateUtils.YMD);
            String filePath= basedir+"/exportMovieUser/"+timeStr+"/";
            FileUtils.existOrmkdir(filePath);
            String fileName="movieUser_"+DateUtils.format(new Date(),DateUtils.YMD_DASH_WITH_TIME_STR)+".xlsx";
            filePath=filePath+fileName;

            List<Map<String, Object>> rows = new ArrayList<>();
            if(list.size()>0)
            {
                int index=1;
                for(TbMovieUserBill item:list){
                    Map<String, Object> row = new LinkedHashMap<>();
                    //序号
                    row.put("序号", index);
                    rows.add(row);
                    index++;
                }
            }
            // 通过工具类创建writer，默认创建xls格式
            ExcelWriter writer = ExcelUtil.getWriter(filePath);
            // 一次性写出内容，使用默认样式，强制输出标题
            writer.write(rows, true);
            Font font = writer.createFont();
            font.setFontHeightInPoints((short) 12); //字体高度
            font.setFontName("微软雅黑");
            writer.getStyleSet().setFont(font, false);
            StyleSet styleSet = writer.getStyleSet();
            styleSet.setAlign(HorizontalAlignment.CENTER, VerticalAlignment.CENTER);
            writer.setStyleSet(styleSet);
            Sheet sheet = writer.getSheet();
            for (int i = 0; i < 100; i++) {
                sheet.autoSizeColumn(i);
            }
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            writer.flush(out, true);
            url="/admin/v1/common/downloadExcel?filePath=/exportMovieUser/"+timeStr+"/"+fileName;
            // 关闭writer，释放内存
            writer.close();
            out.close();
        }catch (Exception e){
            e.printStackTrace();
        }
        log.info("exportData...");
        return url;
    }
}
